/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.lotteryanalyze;

import com.thienloc.omap.entity.GiaiThuong;
import com.thienloc.omap.entity.Kqxs;
import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Tran Tat Thanh
 */
public class WebAnalyzer {
    
    private Pattern[] patterns;
    
    public WebAnalyzer(Pattern[] patterns) {
        this.patterns = patterns;
    }
    
    public Kqxs analyzeKqxs(String rawString) throws Exception {
        String s = normalizeString(rawString);
        Kqxs kqxs = new Kqxs();
        ArrayList<GiaiThuong> list_giai = new ArrayList<GiaiThuong>();
        
        for (int i = 0; i < patterns.length; i++) {
            GiaiThuong giaiThuong = new GiaiThuong();
            giaiThuong.setTenGiai(patterns[i].getTenGiai());
            
            String methodName = "setBoSo";
            for (int j = 0; j < patterns[i].getSoluongboso(); j++) {
                
                Method method = GiaiThuong.class.getMethod(methodName + (j + 1), String.class);
                method.invoke(giaiThuong, s.substring(0, patterns[i].getChieudaiboso()));
                s = s.substring(patterns[i].getChieudaiboso(), s.length());
            }
            list_giai.add(giaiThuong);
        }
        if (s.length() != 0) {
            throw new Exception("Invalid pattern");
        }
        
        kqxs.setGiaiThuongList(list_giai);
        return kqxs;
        
        
    }
    
    private String normalizeString(String s) {
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            String s1 = s.substring(i, i + 1);
            
            if (s1.getBytes()[0] >= 48 && s1.getBytes()[0] <= 57) {
                result += s1;
            }
        }
        return result;
    }
    
    public static void main(String args[]) {
        Pattern mb[] = new Pattern[]{
            new Pattern("Giải đặc biệt", 1, 5),
            new Pattern("Giải nhất", 1, 5),
            new Pattern("Giải nhì", 2, 5),
            new Pattern("Giải ba", 6, 5),
            new Pattern("Giải tư", 4, 4),
            new Pattern("Giải năm", 6, 4),
            new Pattern("Giải sáu", 3, 3),
            new Pattern("Giải bảy", 2, 4)
        };
        
        try {
            String str = FileUtils.readFileToString(new File("d:\\kq.txt"));
            WebAnalyzer analyzer = new WebAnalyzer(mb);
            analyzer.analyzeKqxs(str);
        } catch (Exception ex) {
            LoggerFactory.getLogger(WebAnalyzer.class.getName()).error("", ex);
        }
        
    }
}
